#!/usr/bin/env python
# coding:utf-8


import os,sys
import codecs
import re
from WorkPath import *
import pyExcelerator as pE

LOG_FILE = codecs.open('log.txt','w','utf-8') #sys.stdout

def CColA2N(colName):
	""" Convert excel colume to number"""
	n = 0
	for c in colName:
		n = n*(ord('Z')-ord('A')+1) + (ord(c)-ord('A'))
	return n

THIS_DATA_DIR = DATA_DIR + r'\VoiceID'
FROM_EXCEL_FILE = THIS_DATA_DIR + r'\Voice_ID_list_V15.xls'
TO_EXCEL_FILE = THIS_DATA_DIR + r'\S.xls'

LANGS = ('International English', 'US English', 'UK English', 'German', 'French', 'Dutch', 'Flemmish', 'Spanish',
			'Italian', 'Swedish', 'Danish', 'Norwegian', 'Portuguese', 'Russian')
LANGS_START_COL = 1
LANGS_POS_COL = ( n*2 + LANGS_START_COL for n in range(len(LANGS)))
LANG_COL_PAIRS = zip(LANGS, LANGS_POS_COL)
MAX_ROW = 2000

CONTENT_SHEETS = range(1,8)
os.chdir(THIS_DATA_DIR)

f = pE.parse_xls(FROM_EXCEL_FILE)

def ProcContent(s):
	oris = s
	s = unicode(s)
	sp = True
	if re.match(u'\(.*\)\s*(.*?)\s*\[.*\]\s*\(.*\)\s*$', s):				# (*)*[*](*)
		s = re.match(u'\(.*\)\s*(.*?)\s*\[.*\]\s*\(.*\)\s*$', s).group(1)
	elif re.match(u'\s*.*?\s*（(.*?)）\s*$', s):							# *（×）
		s = re.match(u'\s*.*?\s*（(.*?)）\s*$', s).group(1)
	elif re.match(u'\s*.*?\s*\((.*?)\)\s*$', s):							# *(*)
		s = re.match(u'\s*.*?\s*\((.*?)\)\s*$', s).group(1)
	elif re.match(u'\s*（(.*?)）\s*$', s):									# (*)
		s = re.match(u'\s*（(.*?)）\s*$', s).group(1)			
	else:
		if s.find(u'(')>=0 or s.find(u')')>=0 or s.find(u'（')>=0 \
				or s.find(u'）')>=0 or s.find(u'《')>=0 or s.find(u'<')>=0:
			print >> LOG_FILE, 'Unexpected content:', s
		sp = False
	if sp:
		print >> LOG_FILE, oris, '->', s
	s = unicode(s) + u'\0'
	s = s.encode('utf-16')
	if s.startswith('\xff\xfe') or s.startswith('\xfe\xff'):
		s = s[2:]
	return s

def GetLangPhraseWorkbook(wfname, wtname):
	wt = pE.Workbook()
	wf = pE.parse_xls(wfname)
	for lp in LANG_COL_PAIRS:
		" for each languages"
		print >> LOG_FILE, lp
		wts = wt.add_sheet(lp[0])  # language sheet to write
		wts_r = 0                  # language sheet write column
		for fsheet in CONTENT_SHEETS:
			""" Sheet number of FromWorkbook"""
			k = wf[fsheet][1].keys()
			for row in range(MAX_ROW):
				k1 = (row, lp[1])
				k2 = (row, lp[1]+1)
				if k1 in k and k2 in k:
					wts.write(wts_r, 0, (wf[fsheet][1][k1]))
					wts.write(wts_r, 1, (wf[fsheet][1][k2]))
					wts.write(wts_r, 2, 1)
					wts_r = wts_r +1
	wt.save(wtname)



def CreateTTSFile(wfname):
	os.chdir(THIS_DATA_DIR)
	wf = pE.parse_xls(wfname)
	for sheet in wf:
		print >> LOG_FILE, sheet[0]
		k = sheet[1].keys()
		os.mkdir(sheet[0])
		os.chdir(sheet[0])
		for row in range(MAX_ROW):
			if (row, 0) in k and (row, 1) in k:
				ttsFilename = sheet[1][(row,0)]
				ttsContent = ProcContent(sheet[1][(row,1)])
				# file name
				if isinstance(ttsFilename, long) or isinstance(ttsFilename, float):
					ttsFilename = int(ttsFilename)
				ttsFilename = unicode(ttsFilename) + u'.tts'
				if os.path.exists(ttsFilename):
					print >> LOG_FILE, 'File:', os.path.abspath(ttsFilename), 'already exists'
				ttsf = open(ttsFilename, 'w')
				ttsf.write(ttsContent)
				ttsf.close()
		os.chdir(THIS_DATA_DIR)



def __main__():
	if '--excel' in sys.argv or '-e' in sys.argv:
		GetLangPhraseWorkbook(FROM_EXCEL_FILE, TO_EXCEL_FILE)
	if '--tts' in sys.argv or '-t' in sys.argv:
		CreateTTSFile(TO_EXCEL_FILE)


if __name__ == '__main__':
	__main__()


